package com.yhb.service.impl;

import com.yhb.conf.ResultCode;
import com.yhb.dao.PlanActionMapper;
import com.yhb.dao.PlanMapper;
import com.yhb.model.ChannelFlow;
import com.yhb.model.Plan;
import com.yhb.model.User;
import com.yhb.service.CardService;
import com.yhb.service.PlanService;
import com.yhb.utils.DateUtils;
import me.edzh.spring.bootstrap.utils.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class PlanServiceImpl implements PlanService {
    @Autowired
    private CardService cardService;

    @Autowired
    private PlanMapper planMapper;

    @Autowired
    private PlanActionMapper planActionMapper;



    @Transactional
    @Override
    public void addPlan(Plan plan, User user) {
        cardService.cardWithOwnerCheck(plan.getCardId(), user.getId()); // 检查是否是卡主人
        plan.setUserId(user.getId());


        if (plan.getType() == Plan.Type.PAYBACK) { // 好还

            plan.setWithdrawCardId(plan.getCardId());
            plan.setStatus(Plan.Status.EXECUTING);

            planMapper.insertReturnPlan(plan);

            insertFlows(plan.getFlows(), plan, plan.getUserId(), plan.getLocalization());

        } else if (plan.getType() == Plan.Type.CHEAT) { // 好收
            cardService.cardWithOwnerCheck(plan.getWithdrawCardId(), user.getId()); // 检查是否是卡主人
        } else {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "type field missed");
        }
    }


    private void insertFlows(List<ChannelFlow> flows, Plan plan, String userId, String localization) {
        List<ChannelFlow> buffer = new ArrayList<>();
        int nowDateString = -1;

        for (ChannelFlow flow : flows) {
            int dateString = Integer.parseInt(DateUtils.getDateString(flow.getExecutionTime()));

            // 这里和下面同步改
            if (dateString != nowDateString) {
                if (nowDateString != -1 && buffer.size() != 0) {
                    planActionMapper.insertFlows(buffer, nowDateString + "", plan.getId(), userId, localization);
                    buffer.clear();
                }
            }

            nowDateString = dateString;
            if (flow.getType() == ChannelFlow.Type.CONSUME) flow.setCardId(plan.getCardId());
            else if (flow.getType() == ChannelFlow.Type.REMIT) flow.setCardId(plan.getWithdrawCardId());

            flow.setStatus(ChannelFlow.Status.PENDING);
            buffer.add(flow);

        }

        // 这里和上面同步改
        if (nowDateString != -1 && buffer.size() != 0) {
            planActionMapper.insertFlows(buffer, nowDateString + "", plan.getId(), userId, localization);
            buffer.clear();
        }
    }

    @Override
    public List<Plan> userReturnPlanList(String userId) {
        return planMapper.userReturnPlan(userId);
    }

    @Override
    public Plan returnPlan(String planId, User user) {
        Plan plan = planMapper.returnPlan(planId);
        if (plan == null || !plan.getUserId().equals(user.getId())) throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "计划不存在");

        Calendar c = new Calendar.Builder().setInstant(plan.getCreateTime()).build();

        String endDateString = DateUtils.getDateString(plan.getEndDate());
        List<ChannelFlow> actions = new ArrayList<>();
        String dateString = null;
        do {
            dateString = DateUtils.getDateString(c);
            try {
                actions.addAll(planActionMapper.actions(dateString, planId));

            } catch (BadSqlGrammarException e) {
                // 可能会出现分片表不存在, 直接忽略异常继续
            }
            c.add(Calendar.DAY_OF_MONTH, 1);
        } while (!endDateString.equals(dateString));
        plan.setFlows(actions);
        return plan;
    }
}
